package com.qp.bookkeeping.common.wx.controller;

import cn.hutool.json.JSONUtil;
import com.qp.bookkeeping.business.book.model.Do.UserDo;
import com.qp.bookkeeping.business.common.Exception.BusinessException;
import com.qp.bookkeeping.common.model.req.WxLoginReq;
import com.qp.bookkeeping.common.model.rsp.BaseRsp;
import com.qp.bookkeeping.common.wx.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("wx")
@Slf4j
public class WxController {
    @Resource
    WxService wxService;

    /**
     * 第一次登录或重新登录，使用微信授权码登录
     * @param loginRsp
     * @return 登录信息
     */
    @PostMapping("loginWithCode")
    public BaseRsp<UserDo> loginWithCode(@RequestBody WxLoginReq loginRsp) {
        log.info("请求入参code: " + JSONUtil.toJsonStr(loginRsp));
        UserDo userDo;
        try {
            userDo = wxService.loginWithCode(loginRsp);
        } catch (BusinessException e) {
            return BaseRsp.fail(e.getCode(), e.getMessage());
        }

        return BaseRsp.success(userDo);
    }

    @PostMapping("loginWithToken")
    public BaseRsp<UserDo> loginWithToken(@RequestBody WxLoginReq loginRsp) {
        log.info("请求入参code: " + JSONUtil.toJsonStr(loginRsp));
        UserDo userDo;
        try {
            userDo = wxService.loginWithToken(loginRsp.getWxToken());
        } catch (BusinessException e) {
            return BaseRsp.fail(e.getCode(), e.getMessage());
        }

        return BaseRsp.success(userDo);
    }

    @PostMapping("saveUserAndLogin")
    public BaseRsp<UserDo> saveUserAndLogin(@RequestBody WxLoginReq loginRsp) {
        UserDo userDo;
        try {
            userDo = wxService.saveAndLogin(loginRsp);
        } catch (BusinessException e) {
            return BaseRsp.fail(e.getCode(), e.getMessage());
        }

        return BaseRsp.success(userDo);
    }
}
